<?php

namespace App\Services\Platform;

use App\Core\Traits\Numeral;
use App\Exports\Platform\SettlementUsdExport;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\Platform\Settlement\Day as StatsDay;
use App\Models\Admin\Stats\Platform\Settlement\Month as StatsMonth;
use App\Exports\Platform\SettlementExport;
use Helper\Timed;

class SettlementService extends Service
{
    use DatabaseMysql, Numeral;

    /**
     * 导出数据
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return false|void
     */
    private function export($query, $request, bool $export)
    {
        if (!$export) {
            return false;
        }
        // 前端排序
        $this->makeOrderParam($request, $query);
        // 平台信息
        $query->with('org:code,name');
        // 导出文件
        SettlementExport::query($query)->download();
    }

    /**
     * 获取数据列表【天】
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function day($request, $export = false)
    {
        return $this->getList(StatsDay::query(), $request, $export);
    }

    /**
     * 获取数据列表【月】
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function month($request, $export = false)
    {
        $datetime = $request->input('datetime');

        if (!empty($datetime)) {
            $request->merge(['datetime' => [
                Timed::getMonthCurrentTimed($datetime[0]),
                Timed::getMonthCurrentTimed($datetime[1]),
            ]]);
        }

        return $this->getList(StatsMonth::query(), $request, $export);
    }

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
     */
    public function getList($query, $request, $export)
    {
        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 筛选【平台】【排除】
        $this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query);
        // 筛选【币种】
        $this->makeWhereParam($request, 'currency', $query);
        // 筛选【币种】【排除】
        $this->makeWhereParamNot($request, 'currency_exclude', $query, 'currency');

        // 导出数据
        $this->export($query, $request, $export);

        // 数据条数
        $total = (clone $query)->count();
        // 统计数据
        $stats = $this->getStats(clone $query);
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->with('org:code,name')->get();

        return [
            $collection,
            $total,
            $stats
        ];
    }

    /**
     * 获取统计信息
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return array
     */
    private function getStats($query)
    {
        // USD
        $usd = (clone $query)->getQuery()->selectRaw(implode(',', [
            "IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_num",
            "IFNULL(CAST(SUM(usd->'$.amount') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS amount",
            "IFNULL(CAST(SUM(usd->'$.revenue') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS revenue",
        ]))->first();

        // 分币种
        $sts = $query->getQuery()->selectRaw(implode(',', [
            'SUM(bet_num) as bet_num',
            'SUM(amount) as amount',
            'SUM(revenue) as revenue',
            'currency',
        ]))
            ->groupBy('currency')
            ->get();

        return [
            'usd' => $usd,
            'sts' => $sts,
        ];
    }

    /**
     * 获取平台统计USD
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return \Illuminate\Database\Eloquent\Collection[]|array[]
     */
    public function getUsd($request, $export = false)
    {
        $query = StatsDay::query();

        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 筛选【平台】【排除】
        $this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query);
        // 筛选【币种】
        $this->makeWhereParam($request, 'currency', $query);
        // 筛选【币种】【排除】
        $this->makeWhereParamNot($request, 'currency_exclude', $query, 'currency');

        // 查询数据
        $collection = (clone $query)->selectRaw(implode(',', [
            'plat_code', 'GROUP_CONCAT(DISTINCT rate) as rate',
            "IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_num",
            "IFNULL(CAST(SUM(usd->'$.amount') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS amount",
            "IFNULL(CAST(SUM(usd->'$.revenue') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS revenue",
        ]))
            ->groupBy('plat_code')
            ->orderBy(
                $request->input('order_column', 'revenue'),
                $request->input('order', 'desc')
            )
            ->with('org:code,name')
            ->get();

        // rate去重
        $collection->transform(function ($item) {
            $item['rates'] = explode(',', $item['rate']);
            return $item;
        });

        // 导出数据
        if ($export) {
            SettlementUsdExport::collection($collection)->download();
        }

        // 合计USD
        $stats = $query->getQuery()->selectRaw(implode(',', [
            "IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_num",
            "IFNULL(CAST(SUM(usd->'$.amount') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS amount",
            "IFNULL(CAST(SUM(usd->'$.revenue') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS revenue",
        ]))->first();

        return [
            $collection,
            $stats
        ];
    }
}
